package asteroids.model.expressions;

import java.util.HashMap;
import java.util.Map;

import asteroids.model.*;
import asteroids.model.types.T;

/**
 * A subclass of expression (E) that represents all the Binary composed expressions
 * 
 * All binary expressions have a left and a right operand
 * 
 * @version 1.0
 * 
 * @author	Thijs Peirelinck & Wouter Parys
 *
 */
public abstract class BinaryExpression extends ComposedExpression {

	private E leftOperand;
	private E rightOperand;
	
	public BinaryExpression(E leftOperand, E rightOperand) {
		this.leftOperand = leftOperand;
		this.rightOperand = rightOperand;
	}
	
	@Override
	public abstract boolean isValidExpression(); 
	
	@Override
	public abstract Object getValue();
	
	public E getLeftOperand() {
		return leftOperand;
	}
	
	public E getRightOperand() {
		return rightOperand;
	}
	
	public void setLeftOperand(E expr) {
		this.leftOperand = expr;
	}
	
	public void setRightOperand(E expr) {
		this.rightOperand = expr;
	}

	@Override
	public abstract String getReturnType();
	
	@Override
	public abstract String toString();
	
	@Override
	public void validate(HashMap<String, E> variables) {
		if(this.getLeftOperand() instanceof Variable) {
			setLeftOperand(super.getValidatedOperand(variables, this.getLeftOperand()));	
		}
		else if(this.getLeftOperand() instanceof ComposedExpression) {
			((ComposedExpression)this.getLeftOperand()).validate(variables);
		}
		if(this.getRightOperand() instanceof Variable) {
			setRightOperand(super.getValidatedOperand(variables, this.getRightOperand()));
		}
		else if(this.getRightOperand() instanceof ComposedExpression) {
			((ComposedExpression)this.getRightOperand()).validate(variables);
		}
	}
	
	@Override
	public void setExecuter(Ship executer) {
		getLeftOperand().setExecuter(executer);
		getRightOperand().setExecuter(executer);
	}
	
	@Override
	public boolean typeCheck(Map<String, T> globals) {
		//for a binary expression the returnTypes of both the operands need to be the same
		String typeLeft;
		String typeRight;
		if(this.getLeftOperand() instanceof Variable) {
			if(globals.get(getLeftOperand().getValue()) == null)
				return false;
			typeLeft = globals.get(getLeftOperand().getValue()).getReturnType();
		}
		else {
			if(!getLeftOperand().typeCheck(globals))
				return false;
			typeLeft = getLeftOperand().getReturnType();
		}
		if(this.getRightOperand() instanceof Variable) {
			if(globals.get(getRightOperand().getValue()) == null)
				return false;
			typeRight = globals.get(getRightOperand().getValue()).getReturnType();
		}
		else  {
			if(!getRightOperand().typeCheck(globals))
				return false;
			typeRight = getRightOperand().getReturnType();
		}
		return typeLeft.equals(typeRight);
	}
	

}
